package pers.gxm.security.hello.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import pers.gxm.security.hello.mapper.MenuMapper;
import pers.gxm.security.hello.mapper.UserMapper;
import pers.gxm.security.hello.pojo.LoginUser;
import pers.gxm.security.hello.pojo.User;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//      TODO  1.认证
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(userWrapper);
        if(user == null){
            throw new RuntimeException("用户名不存在");
        }


//        TODO 2.授权
//        TODO  2.1 本来应该从数据库中获取权限，现在先将权限写死
//        List<String> list = new ArrayList<>(Arrays.asList("testHello","test01"));
        List<String> list = menuMapper.selectPermsByUserId(user.getId());
        LoginUser loginUser = new LoginUser(user,list);


        return loginUser;
    }
}
